package com.sosee.cgfw.friends;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.sosee.cgfw.R;
import com.sosee.cgfw.utils.Constans;
import com.sosee.cgfw.utils.LogUtils;
import com.sosee.cgfw.utils.Utils;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

//import com.amap.api.location.AMapLocationClient;
//import com.amap.api.location.AMapLocationClientOption;

/**
 * Created by Thinkpad on 2016/3/1.
 * //附近的人activity
 */
public class FriendsNear extends Activity implements AdapterView.OnItemClickListener {
    private ListView friends_name;
    private HttpUtils httpUtils;
    private List<NearData.Data> data;
    private Context context;
    private String ID1;

    private  TextView friends_addstuta;
    private MyNearAdapter myNearAdapter;
    List<FriendsListData.Data> datas;
//    String[] cityName={};
    List<String> cityName = new ArrayList<String>();
    private String idss;
    private String stuta;

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }




    public LocationClient mLocationClient = null;
    public BDLocationListener myListener = new MyLocationListener();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friends_near);

        mLocationClient = new LocationClient(getApplicationContext());     //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);    //注册监听函数

        initLocation();
        mLocationClient.start();

        context=this;
        httpUtils = new HttpUtils();
        init();
    }


    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span=1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }

    private void init() {
       friends_name = (ListView) findViewById(R.id.friends_listnear);
//        friends_addstuta= (TextView)findViewById(R.id.friends_addstuta);

        myNearAdapter = new MyNearAdapter();
        friends_name.setAdapter(myNearAdapter);
        friends_name.setOnItemClickListener(this);

        ImageButton friends_back3 = (ImageButton)findViewById(R.id.friends_back3);
        friends_back3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        request();
        requestHttp();

    }

    private void request() {

        httpUtils.send(HttpRequest.HttpMethod.GET, Constans.GETFRIENDSLIST_URL+Constans.userID, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                System.out.println("我是好友列表返回的数据：" + result);


                Gson gson = new Gson();
                FriendsListData friendsListData = gson.fromJson(result, FriendsListData.class);
                if("success".equals(friendsListData.getStatus())){

                datas = friendsListData.getData();

                for (int i = 0; i < datas.size(); i++) {
                    String ID = datas.get(i).getFriends().getID();
                    //吧名字赋值给name
                    cityName.add(ID);
                }

                }else{

                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                Utils.showToast("网络加载异常");
            }
        });

    }

    //这是用于请求后台返回附近的人得。
    private void requestHttp() {
        String latitude = SharedPreferencesUtils.getString(this, "Latitude");//维度
        String Longitude = SharedPreferencesUtils.getString(this, "Longitude");//经度

        System.out.println("金维度------" + latitude+"-------"+Longitude);

        httpUtils.configCurrentHttpCacheExpiry(100);

            httpUtils.send(HttpRequest.HttpMethod.GET, Constans.GETNEAR_URL+Constans.userID+"&lon="+Longitude+"&lat="+latitude, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String s = responseInfo.result;
                System.out.println("这是返回的附近的人" + s);
                LogUtils.log_i("这是返回的附近的人" + s);

                Gson gson = new Gson();
                NearData nearData = gson.fromJson(s, NearData.class);
                data = nearData.getData();
                myNearAdapter.notifyDataSetChanged();

            }

            @Override
            public void onFailure(HttpException e, String s) {

                Utils.showToast("网络获取异常");
            }
        });
    }





    public class MyNearAdapter extends BaseAdapter{

        @Override
        public int getCount() {

            return data==null?0:data.size();
        }

        @Override
        public Object getItem(int position) {
            return data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

                final ViewHolder holder;
                if (convertView == null) {

                    holder = new ViewHolder();
                    convertView = LayoutInflater.from(context).inflate(R.layout.friends_listnear_item, null);

                    if(position%2==0){
                        //这里是改变条目背景色的
                        convertView.setBackgroundResource(R.drawable.kuang1);

                    }else{
                        convertView.setBackgroundResource(R.drawable.kuang2);

                    }
                    holder.friends_name1 = (TextView) convertView.findViewById(R.id.friends_name);
                    holder.friends_company1 = (TextView) convertView.findViewById(R.id.friends_company);
                    holder.friends_sort1 = (TextView) convertView.findViewById(R.id.friends_sort);
                    holder.friends_addstuta1 = (TextView) convertView.findViewById(R.id.friends_addstuta);




                    convertView.setTag(holder);
                } else {
                    holder = (ViewHolder) convertView.getTag();
                }

                holder.friends_name1.setText(data.get(position).getNickname());
                holder.friends_company1.setText(data.get(position).getCompany());
                holder.friends_sort1.setText(data.get(position).getDuty());
                stuta = holder.friends_addstuta1.getText().toString();
                return convertView;



        }

        class ViewHolder {
            public TextView friends_name1;
            public TextView friends_company1;
            public TextView friends_sort1;
            public TextView friends_addstuta1;

        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //
        switch (parent.getId()){
            case R.id.friends_listnear:
                //这是
                Intent intent = new Intent(FriendsNear.this,FriendsInfos.class);
                System.out.println("这是传递过去的好友id" + data.get(position).getID());
                intent.putExtra("idss", data.get(position).getID());



                startActivity(intent);
                break;
            default:
                break;
        }
    }

    public class MyLocationListener implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            //Receive Location
            StringBuffer sb = new StringBuffer(256);
            sb.append("time : ");
            sb.append(location.getTime());
            sb.append("\nerror code : ");
            sb.append(location.getLocType());
            sb.append("\nlatitude : ");
            sb.append(location.getLatitude());
            sb.append("\nlontitude : ");
            sb.append(location.getLongitude());
            sb.append("\nradius : ");
            sb.append(location.getRadius());
            if (location.getLocType() == BDLocation.TypeGpsLocation){// GPS定位结果
                sb.append("\nspeed : ");
                sb.append(location.getSpeed());// 单位：公里每小时
                sb.append("\nsatellite : ");
                sb.append(location.getSatelliteNumber());
                sb.append("\nheight : ");
                sb.append(location.getAltitude());// 单位：米
                sb.append("\ndirection : ");
                sb.append(location.getDirection());// 单位度
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\ndescribe : ");
                sb.append("gps定位成功");

            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation){// 网络定位结果
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                //运营商信息
                sb.append("\noperationers : ");
                sb.append(location.getOperators());
                sb.append("\ndescribe : ");
                sb.append("网络定位成功");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                sb.append("\ndescribe : ");
                sb.append("离线定位成功，离线定位结果也是有效的");
            } else if (location.getLocType() == BDLocation.TypeServerError) {
                sb.append("\ndescribe : ");
                sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                sb.append("\ndescribe : ");
                sb.append("网络不同导致定位失败，请检查网络是否通畅");
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                sb.append("\ndescribe : ");
                sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
            }
            sb.append("\nlocationdescribe : ");
            sb.append(location.getLocationDescribe());// 位置语义化信息
            List<Poi> list = location.getPoiList();// POI数据
            if (list != null) {
                sb.append("\npoilist size = : ");
                sb.append(list.size());
                for (Poi p : list) {
                    sb.append("\npoi= : ");
                    sb.append(p.getId() + " " + p.getName() + " " + p.getRank());
                }
            }
            Log.i("BaiduLocationApiDem", sb.toString());

            SharedPreferencesUtils.putString(FriendsNear.this, "Latitude", String.valueOf(location.getLatitude()));//维度
            SharedPreferencesUtils.putString(FriendsNear.this,"Longitude", String.valueOf(location.getLongitude()));//经度

        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        if(null!=mLocationClient){
            mLocationClient.stop();

        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        if(null!=mLocationClient){
            mLocationClient.stop();
           
        }

    }
}
